using Essensoft.Paylink.WeChatPay;
using Essensoft.Paylink.WeChatPay.V2;
using Essensoft.Paylink.WeChatPay.V2.Request;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace XUCore.WeChat
{
    public class WeChatPayRsaService
    {
        private readonly IWeChatPayClient client;
        private readonly WeChatFuncs weChatFuncs;
        public WeChatPayRsaService(IServiceProvider serviceProvider)
        {
            this.client = serviceProvider.GetRequiredService<IWeChatPayClient>();
            this.weChatFuncs = serviceProvider.GetRequiredService<WeChatFuncs>();
        }
        /// <summary>
        /// 获取RSA加密公钥（项目初始配置的时候用）
        /// </summary>
        /// <param name="weChatType">微信类型</param>
        /// <param name="app">应用标识</param>
        public async Task<string> GetPublicKey(WeChatType weChatType, string app)
        {
            var wechatPayOptions = default(WeChatPayOptions);

            if (weChatType == WeChatType.PublicAccount)
                wechatPayOptions = weChatFuncs.GetWeChatOptions(app)?.WeChatPayOptions;
            else
                wechatPayOptions = weChatFuncs.GetMiniProgramOptions(app)?.WeChatPayOptions;

            if (wechatPayOptions == null)
                throw new WeChatSdkException($"{nameof(WeChatPayRsaService)}，App:{app}，获取微信支付配置失败。");

            var request = new WeChatPayRiskGetPublicKeyRequest();
            var response = await client.ExecuteAsync(request, wechatPayOptions);

            return response.Body;
        }
    }
}